package com.wpp.register.loaderbalance;

import com.sun.org.apache.xpath.internal.objects.XNull;
import com.wpp.register.ServerInfo;
import com.wpp.register.converter.ServerInfoConvert;
import com.wpp.register.loaderbalance.LoaderBalance;
import com.wpp.register.metric.ResponseTimeMetricHolder;
import com.wpp.register.metric.TimeMetric;

import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @Classname RandomLoaderBalance
 * @Description TODO
 * @Date 2020/12/7 23:44
 * @Created by wpp25
 */
public class MinTimeLoaderBalance implements LoaderBalance {

    // TODO: 2020/12/7
    @Override
    public ServerInfo balance(List<ServerInfo> serverInfoList) {
        System.out.printf("当前服务列表：%s %n ",serverInfoList);
        ServerInfo provideServer = null;
        Map<String, TimeMetric> timeMetricMap = ResponseTimeMetricHolder.getInstance().getTimeMetricMap();
        System.out.printf("当前时间控件服务列表：%s %n ",timeMetricMap);
        if (timeMetricMap.size() == 0) {
            provideServer = new RandomLoaderBalance().balance(serverInfoList);
            return provideServer;
        }
        TimeMetric timeMetric = timeMetricMap.values().stream().min(Comparator.comparing(TimeMetric::getLastTimeConsuming)).get();
        ServerInfo timeMetricServer = ServerInfoConvert.convert(timeMetric.getServerAddress());
        for (ServerInfo serverInfo : serverInfoList) {
            if (serverInfo.getIp().equals(timeMetricServer.getIp()) && serverInfo.getPort() == timeMetricServer.getPort()) {
                provideServer =  serverInfo;
                System.out.printf("本地提供服务的是：%s %n ",timeMetric.toString());
                break;
            }
        }

        return provideServer;
    }
}
